package com.uhylab.uhuvinetest.qrcamera.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.uhylab.uhuvinetest.DaoInset;
import com.uhylab.uhuvinetest.JNIJson;
import com.uhylab.uhuvinetest.R;
import com.uhylab.uhuvinetest.activity.UHHistoryActivity;
import com.uhylab.uhuvinetest.base.UHBase;
import com.uhylab.uhuvinetest.bean.History_Content;
import com.uhylab.uhuvinetest.dao.DaoSingleton;
import com.uhylab.uhuvinetest.dao.LocalHistory;
import com.uhylab.uhuvinetest.dao.LocalHistoryDao;
import com.uhylab.uhuvinetest.utils.VolleySingleton;
import com.uhylab.uhuvinetest.utils.sharedpreutils.SharedPreUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ResultActivity extends Activity {

    private ImageView mResultImage;
    private SimpleDraweeView mResultText;
    private CreateBitmapThread createBitmapThread;
    private Handler handler;
    private VolleySingleton volleySingleton;
    private float HFloat;
    private float HFloat1;
    private float HFloat2;
    private float HFloat3;
    private float HFloat4;
    private float HFloat5;
    private float HFloat6;
    private float HFloat7;
    private float HFloat8;
    private float HFloat9;
    private float HFloat10;
    private String t;
    private String colorSetion[] = {
            "leukocytes_status", "nitrite_status", "urobilinogen_status", "protein_status",
            "ph_status", "blood_status",
            "gravity_status", "ketones_status", "bilirubin_status", "glucose_status", "ascorbicacid_status"
    };
    private LocalHistoryDao localHistoryDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_result);
        volleySingleton = VolleySingleton.getVolleySingleton(getApplicationContext());
        Bundle extras = getIntent().getExtras();
        mResultImage = (ImageView) findViewById(R.id.result_image);
        mResultText = (SimpleDraweeView) findViewById(R.id.result_text);
        Uri uri2 = Uri.parse("asset:///gif.gif");
        /**
         * 下面是主要代码：
         */
        DraweeController draweeController = Fresco.newDraweeControllerBuilder()
                .setAutoPlayAnimations(true)//自动播放动画
                .setUri(uri2)//路径
                .build();
        mResultText.setController(draweeController);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        t = format.format(new Date());
        localHistoryDao = DaoSingleton.getInstance().getLocalHistoryDao();
        // Init the handler
        initHandler();
        // set  Bundle from the above data
        initBundle(extras);
    }

    private void initHandler() {
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {

                switch (msg.what) {
                    case 0:
                        Bundle obj = (Bundle) msg.obj;
                        float[] HSV = obj.getFloatArray("list");
                        int weidongses[] = obj.getIntArray("weidongs");
                        int liumingses[] = obj.getIntArray("liumings");
                        final float[] H = new float[11];

                        for (int i = 0; i < HSV.length / 3; i++) {
                            H[i] = HSV[i * 3 + 0];
                        }



                        JNIJson jniJson = new JNIJson(ResultActivity.this);
//                        HFloat = (H[0] > 180) && (H[0] < 260) ? H[0] + 180 : H[0] + 360;
//                        HFloat1 = (H[1] > 180) && (H[1] < 260) ? H[1] + 180 : H[1] + 360;
                        if ((H[0] > 180) && (H[0] < 280)) {
                            HFloat = H[0] + 180;
                        } else if (H[0] < 180) {
                            HFloat = H[0] + 360;
                        } else if (H[0] >= 280) {
                            HFloat = H[0];
                        }


                        if ((H[1] > 180) && (H[1] < 240)) {
                            HFloat1 = H[1] + 180;
                        } else if (H[1] < 180) {
                            HFloat1 = H[1] + 360;
                        } else if (H[1] >= 240) {
                            HFloat1 = H[1];
                        }

                        HFloat2 = H[2] > 180 ? H[2] : H[2] + 360;
//                        HFloat3 = H[3] > 180 ? H[3] : H[3] + 360;
                        HFloat3 = H[3];


//                        if ((H[3] > 180) && (H[3] < 240)) {
//                            HFloat3 = H[3] + 180;
//                        } else if (H[3] < 180) {
//                            HFloat3 = H[3] + 360;
//                        } else if (H[3] >= 240){
//                            HFloat3 = H[3];
//                        }


                        HFloat4 = H[4] > 180 ? H[4] : H[4] + 360;
                        HFloat5 = H[5] > 180 ? H[5] : H[5] + 360;
                        HFloat6 = H[6] > 180 ? H[6] : H[6] + 360;
//                        HFloat7 = (H[7] > 180) && (H[7] < 240) ? H[7] + 180 : H[7] + 360;

                        if ((H[7] > 180) && (H[7] < 290)) {
                            HFloat7 = H[7] + 180;
                        } else if (H[7] < 180) {
                            HFloat7 = H[7] + 360;
                        } else if (H[7] >= 290) {
                            HFloat7 = H[7];
                        }

//                        HFloat8 = H[8];
//                        if (HFloat8 < 20){
//                        HFloat8 = HFloat8 + 20;
//                        }
//                        HFloat8 = H[8] > 180 ? H[8] : H[8] + 360;
                        if ((H[8] > 180) && (H[8] < 270)) {
                            HFloat8 = H[8] + 180;
                        } else if (H[8] < 180) {
                            HFloat8 = H[8] + 360;
                        } else if (H[8] >= 270) {
                            HFloat8 = H[8];
                        }

                        HFloat9 = H[9];
                        HFloat10 = H[10] > 180 ? H[10] : H[10] + 360;
                        final String[] states = {
                                jniJson.getLeukocytes().get(get_near(jniJson.getS(), HFloat)).getState(),
                                jniJson.getNitrite().get(get_near(jniJson.getNis(), HFloat1)).getState(),
                                jniJson.getUrobilinogen().get(get_near(jniJson.getUrs(), HFloat2)).getState(),
                                jniJson.getProtein().get(get_near(jniJson.getPrs(), HFloat3)).getState(),
                                jniJson.getPh().get(get_near(jniJson.getPhs(), HFloat4)).getState(),
                                jniJson.getBlood().get(get_near(jniJson.getBls(), HFloat5)).getState(),
                                jniJson.getSpecificGravity().get(get_near(jniJson.getSpecifis(), HFloat6)).getState(),
                                jniJson.getKetones().get(get_near(jniJson.getKes(), HFloat7)).getState(),
                                jniJson.getBilirubin().get(get_near(jniJson.getBis(), HFloat8)).getState(),
                                jniJson.getGlucose().get(get_near(jniJson.getGls(), HFloat9)).getState(),
                                jniJson.getAscorbicAcid().get(get_near(jniJson.getAss(), HFloat10)).getState()
                        };
                        // Init network request
                        initRequest(H, states);

                        ArrayList<History_Content> arrayList = new ArrayList<>();
                        History_Content leukocytes = new History_Content();
                        History_Content nitrite = new History_Content();
                        History_Content urobilinogen = new History_Content();
                        History_Content protein = new History_Content();
                        History_Content ph = new History_Content();
                        History_Content blood = new History_Content();
                        History_Content gravity = new History_Content();
                        History_Content ketones = new History_Content();
                        History_Content bilirubin = new History_Content();
                        History_Content glucose = new History_Content();
                        History_Content ascorbicacid = new History_Content();
                        History_Content[] history_contents = {
                                leukocytes, nitrite, urobilinogen, protein, ph, blood, gravity, ketones, bilirubin, glucose, ascorbicacid
                        };
                        String[] strings = {
                                "白细胞", "亚硝酸盐", "尿胆原", "蛋白质", "酸碱度", "潜血", "比重", "酮体", "胆红素", "葡萄糖", "抗坏血酸"
                        };


                        String[] floats = {
                                jniJson.getLeukocytes().get(get_near(jniJson.getS(), HFloat)).getContentValue()
                                        + "" + jniJson.getLeukocytes().get(get_near(jniJson.getS(), HFloat)).getUnit(),
                                jniJson.getNitrite().get(get_near(jniJson.getNis(), HFloat1)).getContentValue()
                                        + "" + jniJson.getNitrite().get(get_near(jniJson.getNis(), HFloat1)).getUnit(),
                                jniJson.getUrobilinogen().get(get_near(jniJson.getUrs(), HFloat2)).getContentValue() + ""
                                        + jniJson.getUrobilinogen().get(get_near(jniJson.getUrs(), HFloat2)).getUnit(),
                                jniJson.getProtein().get(get_near(jniJson.getPrs(), HFloat3)).getContentValue() + "" +
                                        jniJson.getProtein().get(get_near(jniJson.getPrs(), HFloat3)).getUnit(),
                                jniJson.getPh().get(get_near(jniJson.getPhs(), HFloat4)).getContentValue()
                                        + "" + jniJson.getPh().get(get_near(jniJson.getPhs(), HFloat4)).getUnit(),
                                jniJson.getBlood().get(get_near(jniJson.getBls(), HFloat5)).getContentValue() + ""
                                        + jniJson.getBlood().get(get_near(jniJson.getBls(), HFloat5)).getUnit(),
                                jniJson.getSpecificGravity().get(get_near(jniJson.getSpecifis(), HFloat6)).getContentValue()
                                        + "" + jniJson.getSpecificGravity().get(get_near(jniJson.getSpecifis(), HFloat6)).getUnit(),
                                jniJson.getKetones().get(get_near(jniJson.getKes(), HFloat7)).getContentValue()
                                        + "" + jniJson.getKetones().get(get_near(jniJson.getKes(), HFloat7)).getUnit(),
                                jniJson.getBilirubin().get(get_near(jniJson.getBis(), HFloat8)).getContentValue()
                                        + "" + jniJson.getBilirubin().get(get_near(jniJson.getBis(), HFloat8)).getUnit(),
                                jniJson.getGlucose().get(get_near(jniJson.getGls(), HFloat9)).getContentValue()
                                        + "" + jniJson.getGlucose().get(get_near(jniJson.getGls(), HFloat9)).getUnit(),
                                jniJson.getAscorbicAcid().get(get_near(jniJson.getAss(), HFloat10)).getContentValue()
                                        + "" + jniJson.getAscorbicAcid().get(get_near(jniJson.getAss(), HFloat10)).getUnit()
                        };


                        for (int i = 0; i < history_contents.length; i++) {
                            history_contents[i].setName(strings[i]);
                            history_contents[i].setContent(floats[i]);
                            if (states[i].equals("正常")) {
                                history_contents[i].setAnInt(0);
                            } else if (states[i].equals("轻微")) {
                                history_contents[i].setAnInt(1);
                            } else if (states[i].equals("严重")) {
                                history_contents[i].setAnInt(2);
                            } else if (states[i].equals("微量")) {
                                history_contents[i].setAnInt(3);
                            }
                        }

                        for (int i = 0; i < history_contents.length; i++) {
                            arrayList.add(history_contents[i]);
                        }
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date parse;
                        try {
                            parse = sdf.parse(t);
                            DateFormat data = new SimpleDateFormat("yyyy年MM月dd日");
                            DateFormat time = new SimpleDateFormat("HH:mm");
                            String formatData = data.format(parse);
                            String formatTime = time.format(parse);
                            String days[] = {
                                    formatData, formatTime
                            };
                            Intent intent = new Intent(ResultActivity.this, UHHistoryActivity.class);
                            intent.putParcelableArrayListExtra("content", arrayList);
                            intent.putExtra("days", days);
                            intent.putExtra("weidong", weidongses);
                            intent.putExtra("liuming", liumingses);
                            Log.e("TAG","weidong" + weidongses.length);
                            Log.e("TAG","liuming" + liumingses.length);
                            Message message = new Message();
                            message.what = 1;
                            message.obj = intent;
                            handler.sendMessageDelayed(message, 2000);

                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        break;

                    case 1:
                        startActivity((Intent) msg.obj);
                        finish();
                        break;
                    case 2:
                        Bitmap bitmap = (Bitmap) msg.obj;
                        mResultImage.setImageBitmap(bitmap);

                        break;
                }
                return false;
            }


        });
    }


//    private void initRequest(final float[] lists, final String[] daoInsets) {
//        StringRequest request = new StringRequest(Request.Method.POST, UHBase.insertHistory, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String response) {
//
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                String tel = SharedPreUtils.getString(getApplication(), "user_tel", "");
//                DaoInset daoInset = new DaoInset(lists, daoInsets, t, tel);
//                LocalHistory start = daoInset.start();
//                localHistoryDao.insertOrReplace(start);
//            }
//        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                //在这里设置需要post的参数
//                Map<String, String> params = new HashMap<String, String>();
//                String tel = SharedPreUtils.getString(getApplication(), "user_tel", "");
//                for (int i = 0; i < colorSetion.length; i++) {
//                    if (daoInsets[i].equals("正常")) {
//                        params.put(colorSetion[i], "0");
//                    } else if (daoInsets[i].equals("轻微")) {
//                        params.put(colorSetion[i], "1");
//                    } else if (daoInsets[i].equals("严重")) {
//                        params.put(colorSetion[i], "2");
//                    } else if (daoInsets[i].equals("微量")) {
//                        params.put(colorSetion[i], "3");
//                    }
//                }
//                params.put("telephone", tel);
//                params.put("leukocytes", String.valueOf(lists[0]));
//                params.put("nitrite", String.valueOf(lists[1]));
//                params.put("urobilinogen", String.valueOf(lists[2]));
//                params.put("protein", String.valueOf(lists[3]));
//                params.put("ph", String.valueOf(lists[4]));
//                params.put("blood", String.valueOf(lists[5]));
//                params.put("gravity", String.valueOf(lists[6]));
//                params.put("ketones", String.valueOf(lists[7]));
//                params.put("bilirubin", String.valueOf(lists[8]));
//                params.put("glucose", String.valueOf(lists[9]));
//                params.put("ascorbicacid", String.valueOf(lists[10]));
//                params.put("date", t);
//                return params;
//            }
//        };
//
//        if (!SharedPreUtils.getString(getApplication(), "user_tel", "").equals("")) {
//            volleySingleton.addQueue(request, "insertHistory");
//        }
//    }


    private void initRequest(final float[] lists, final String[] daoInsets) {
        String userToken = SharedPreUtils.getString(this, "user_token", null);
        JSONObject jsonObject = new JSONObject();
        Log.e("ResultActivity", "shangchuan");
        try {

            for (int i = 0; i < colorSetion.length; i++) {
                if (daoInsets[i].equals("正常")) {
                    jsonObject.put(colorSetion[i], "0");
                } else if (daoInsets[i].equals("轻微")) {
                    jsonObject.put(colorSetion[i], "1");
                } else if (daoInsets[i].equals("严重")) {
                    jsonObject.put(colorSetion[i], "2");
                } else if (daoInsets[i].equals("微量")) {
                    jsonObject.put(colorSetion[i], "3");
                }
            }
            jsonObject.put("leukocytes", String.valueOf(lists[0]));
            jsonObject.put("nitrite", String.valueOf(lists[1]));
            jsonObject.put("urobilinogen", String.valueOf(lists[2]));
            jsonObject.put("protein", String.valueOf(lists[3]));
            jsonObject.put("ph", String.valueOf(lists[4]));
            jsonObject.put("blood", String.valueOf(lists[5]));
            jsonObject.put("gravity", String.valueOf(lists[6]));
            jsonObject.put("ketones", String.valueOf(lists[7]));
            jsonObject.put("bilirubin", String.valueOf(lists[8]));
            jsonObject.put("glucose", String.valueOf(lists[9]));
            jsonObject.put("ascorbicacid", String.valueOf(lists[10]));
            jsonObject.put("date", t);

            JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, UHBase.newInsertHistory
                    + "token=" + userToken
                    , jsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.e("ResultActivity", "response:" + response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    String tel = SharedPreUtils.getString(getApplication(), "user_tel", "");
                    DaoInset daoInset = new DaoInset(lists, daoInsets, t, tel);
                    LocalHistory start = daoInset.start();
                    localHistoryDao.insertOrReplace(start);
                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Accept", "application/json");
                    headers.put("Content-Type", "application/json; charset=UTF-8");
                    return headers;
                }

            };

            if (!SharedPreUtils.getString(getApplication(), "user_tel", "").equals("")) {
                volleySingleton.addQueue(request, "insertHistory");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e("ResultActivity", "shibai");
        }
    }

    private void initBundle(Bundle extras) {
        if (null != extras) {

            String img = extras.getString("IMG_URI");
            float[] floats = extras.getFloatArray("colors");
            int[] weidongs = extras.getIntArray("weidong");
            int[] liumings = extras.getIntArray("liuming");

            if (img != null) {
                createBitmapThread = new CreateBitmapThread(handler, this, img, mResultImage, floats, weidongs, liumings);
                createBitmapThread.start();
            }
        }
    }

    public static int get_near(float[] array, float target) {
        if (array.length == 0) return -1;
        if (array.length == 1) return 0;
        float[] floa = new float[array.length];
        for (int k = 0; k < floa.length; k++) {
            floa[k] = array[k];
        }
        Arrays.sort(array);
        int min = 0;
        int max = array.length - 1;
        int mid = (min + max) / 2;

        while (max - min > 1) {
            if (target == array[mid]) return mid;
            if (target < array[mid]) max = mid;
            if (target > array[mid]) min = mid;
            mid = (min + max) / 2;
        }

        for (int j = 0; j < floa.length; j++) {
            if (floa[j] == array[array[max] - target < target - array[min] ? max : min]) {
                return j;
            }
        }
        return (array[max] - target) < (target - array[min]) ? max : min;
    }


    @Override
    protected void onPause() {
        super.onPause();
    }
}
